package com.zengyu.toiusuapplication.order;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.zengyu.toiusuapplication.R;
import com.zengyu.toiusuapplication.Utils.SessionManager;
import com.zengyu.toiusuapplication.api.ApiClient;
import com.zengyu.toiusuapplication.api.ApiService;
import com.zengyu.toiusuapplication.change.upLoadComplaintURL;
import com.zengyu.toiusuapplication.model.upLoadComplaintURLModel;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ModifyDetailsActivity extends AppCompatActivity {
    private TextView orderIdTextView, userIdTextView;
    private Long complaintId;

    private EditText editTitle;               // 标题
    private EditText editCellName;            // 小区名
    private EditText editLatitudeLongitude;   // 经纬度
    private EditText editDuration;            // 持续时间
    private EditText editUserEmotion;         // 客户情绪
    private EditText editScene;               // 投诉场景
    private EditText editUserIssue;           // 客户问题现象
    private EditText editHouseAddress;        // 投诉点建筑描述
    private EditText editNetworkMode;         // 手机上网模式+语音方案
    private EditText editAddress;             // 投诉实际地址
    private EditText editNetwork4GLevel;      // 客户终端+品牌型号
    private EditText editBackup;              // 备注
    private Spinner classificationSpinner;    // 分类选择器
    private String selectedClassification = "4G";
    private Button saveButton;                // 保存按钮
    private ImageView imageSignalThumbnail;  //信号测试图
    private ImageView imageSceneThumbnail; // 现场照片图
    private ImageView imageSpeedThumbnail;  // 速率测试图
    private ImageView imageCommunicationThumbnail;  //客户沟通截图
    private EditText editImageSignalURL;
    private EditText editImageSceneURL;
    private EditText editImageSpeedURL;
    private EditText editImageCommunicationURL;
    private SessionManager sessionManager;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sessionManager = SessionManager.getInstance(this);
        token = sessionManager.getToken();
        setContentView(R.layout.activity_modify_details);
        initViews();
        Intent intent = getIntent();
        complaintId = intent.getLongExtra("modifyId", -1);
        if (complaintId == -1) {
            Toast.makeText(this, "无效的投诉ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        fetchComplaintById(complaintId);
        saveButton.setOnClickListener(v -> updateComplaint());
    }

    /**
     * 初始化所有视图控件
     */
    private void initViews() {
        orderIdTextView = findViewById(R.id.order_id_details);
        userIdTextView = findViewById(R.id.user_id_details);
        // EditText 字段初始化
        editTitle = findViewById(R.id.edit_titleDetails);
        editCellName = findViewById(R.id.edit_cellName);
        editLatitudeLongitude = findViewById(R.id.edit_latitude_longitude);
        editDuration = findViewById(R.id.edit_durationLabel);
        editUserEmotion = findViewById(R.id.edit_userEmotionLabel);
        editScene = findViewById(R.id.edit_sceneLabel);
        editUserIssue = findViewById(R.id.edit_userIssueLabel);
        editHouseAddress = findViewById(R.id.edit_houseaddressLabel);
        editNetworkMode = findViewById(R.id.edit_network4GModeLabel);
        editAddress = findViewById(R.id.edit_address);
        editNetwork4GLevel = findViewById(R.id.edit_network4g_level);
        editBackup = findViewById(R.id.edit_backup);
        imageSignalThumbnail = findViewById(R.id.imageSignalThumbnail);
        imageSceneThumbnail = findViewById(R.id.imageSceneThumbnail);
        imageSpeedThumbnail = findViewById(R.id.imageSpeedThumbnail);
        imageCommunicationThumbnail = findViewById(R.id.imageCommunicationThumbnail);
        editImageSignalURL = findViewById(R.id.edit_imageSignalURL);
        editImageSceneURL = findViewById(R.id.edit_imageSceneURL);
        editImageSpeedURL = findViewById(R.id.edit_imageSpeedURL);
        editImageCommunicationURL = findViewById(R.id.edit_imageCommunicationURL);

        classificationSpinner = findViewById(R.id.classificationSpinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item,
                new String[]{"4G", "5G"});
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        classificationSpinner.setAdapter(adapter);
        classificationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedClassification = parent.getItemAtPosition(position).toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedClassification = "4G";
            }
        });

        // 初始化控件时绑定返回按钮
        ImageView icReturn = findViewById(R.id.ic_return);
        icReturn.setOnClickListener(v -> {
            finish(); // 关闭当前 Activity，返回上一页
        });

        saveButton = findViewById(R.id.save_Button);

        // 设置点击事件（模拟打开相册）
        imageSignalThumbnail.setOnClickListener(v -> openImagePicker(editImageSignalURL, imageSignalThumbnail));
        imageSceneThumbnail.setOnClickListener(v -> openImagePicker(editImageSceneURL, imageSceneThumbnail));
        imageSpeedThumbnail.setOnClickListener(v -> openImagePicker(editImageSpeedURL, imageSpeedThumbnail));
        imageCommunicationThumbnail.setOnClickListener(v -> openImagePicker(editImageCommunicationURL, imageCommunicationThumbnail));
    }

    /**
     * 根据 complaintId 请求后端获取投诉详情
     */
    private void fetchComplaintById(Long complaintId) {
        ApiService apiService = ApiClient.getApiService();

        if (!sessionManager.isTokenValid() || TextUtils.isEmpty(token)) {
            Toast.makeText(this, "登录信息失效，请重新登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        Call<upLoadComplaintURLModel> call = apiService.getEditFeedback(complaintId);
        call.enqueue(new Callback<upLoadComplaintURLModel>() {
            @Override
            public void onResponse(Call<upLoadComplaintURLModel> call, Response<upLoadComplaintURLModel> response) {
                if (response.isSuccessful() && response.body() != null) {
                    upLoadComplaintURLModel complaint = response.body();

                    // 回显所有字段
                    editTitle.setText(complaint.getTitle());
                    editCellName.setText(complaint.getCellName());
                    editLatitudeLongitude.setText(complaint.getLatitudeLongitude());
                    editDuration.setText(complaint.getDuration());
                    editUserEmotion.setText(complaint.getUserEmotion());
                    editScene.setText(complaint.getScene());
                    editUserIssue.setText(complaint.getUserIssue());
                    editHouseAddress.setText(complaint.getHouseaddress());
                    editNetworkMode.setText(complaint.getNetworkMode());
                    editAddress.setText(complaint.getAddress());
                    editNetwork4GLevel.setText(complaint.getNetwork4GLevel());
                    editBackup.setText(complaint.getBackup());

                    // 图片 URL 回显
                    editImageSignalURL.setText(complaint.getImageSignalURL());
                    editImageSceneURL.setText(complaint.getImageSceneURL());
                    editImageSpeedURL.setText(complaint.getImageSpeedURL());
                    editImageCommunicationURL.setText(complaint.getImageCommunicationURL());

                    String base_imageUrl = ApiClient.base_ImageUrl;

                    String imageSignalURL = base_imageUrl + complaint.getImageSignalURL();
                    String imageSceneURL = base_imageUrl + complaint.getImageSceneURL();
                    String imageSpeedURL = base_imageUrl + complaint.getImageSpeedURL();
                    String imageCommunicationURL = base_imageUrl + complaint.getImageCommunicationURL();

                    // 加载图片缩略图
                    loadThumbnail(imageSignalThumbnail,imageSignalURL, R.drawable.image1);
                    loadThumbnail(imageSceneThumbnail,imageSceneURL, R.drawable.image1);
                    loadThumbnail(imageSpeedThumbnail, imageSpeedURL, R.drawable.image1);
                    loadThumbnail(imageCommunicationThumbnail, imageCommunicationURL, R.drawable.image1);

                    // 设置不可编辑字段
                    orderIdTextView.setText("订单ID: " + complaint.getId());
                    userIdTextView.setText("提交人ID: " + complaint.getUserId());

                    // 设置不可编辑字段
                    orderIdTextView.setText("订单ID: " + complaint.getId());
                    userIdTextView.setText("提交人ID: " + complaint.getUserId());

                    // 设置分类下拉框
                    classificationSpinner.setSelection(
                            "5G".equals(complaint.getClassificationLabel()) ? 1 : 0);

                } else {
                    Toast.makeText(ModifyDetailsActivity.this, "加载失败: " + response.code(), Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            @Override
            public void onFailure(Call<upLoadComplaintURLModel> call, Throwable t) {
                Toast.makeText(ModifyDetailsActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private void loadThumbnail(ImageView imageView, String url, int placeholderResId) {
        if (!TextUtils.isEmpty(url)) {
            Glide.with(this)
                    .load(url)
                    .placeholder(placeholderResId)
                    .error(placeholderResId)
                    .into(imageView);
        } else {
            imageView.setImageResource(placeholderResId);
        }
    }


    /**
     * 提交更新请求
     */
    private void updateComplaint() {
        String title = editTitle.getText().toString().trim();
        String cellName = editCellName.getText().toString().trim();
        String latitudeLongitude = editLatitudeLongitude.getText().toString().trim();
        String duration = editDuration.getText().toString().trim();
        String userEmotion = editUserEmotion.getText().toString().trim();
        String scene = editScene.getText().toString().trim();
        String userIssue = editUserIssue.getText().toString().trim();
        String houseAddress = editHouseAddress.getText().toString().trim();
        String networkMode = editNetworkMode.getText().toString().trim();
        String address = editAddress.getText().toString().trim();
        String network4GLevel = editNetwork4GLevel.getText().toString().trim();
        String backup = editBackup.getText().toString().trim();

        // 校验必填字段
        if (title.isEmpty() || cellName.isEmpty() || latitudeLongitude.isEmpty()
                || duration.isEmpty() || userEmotion.isEmpty() || scene.isEmpty()
                || userIssue.isEmpty() || houseAddress.isEmpty() || networkMode.isEmpty()
                || address.isEmpty() || network4GLevel.isEmpty()) {
            Toast.makeText(this, "请填写所有必填字段", Toast.LENGTH_SHORT).show();
            return;
        }

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("classificationLabel", selectedClassification);
        requestBody.put("title", title);
        requestBody.put("cellName", cellName);
        requestBody.put("latitudeLongitude", latitudeLongitude);
        requestBody.put("duration", duration);
        requestBody.put("userEmotion", userEmotion);
        requestBody.put("scene", scene);
        requestBody.put("userIssue", userIssue);
        requestBody.put("houseaddress", houseAddress);
        requestBody.put("network4GMode", networkMode);
        requestBody.put("address", address);
        requestBody.put("network4GLevel", network4GLevel);
        requestBody.put("backup", backup);
        requestBody.put("imageSignalURL", editImageSignalURL.getText().toString().trim());
        requestBody.put("imageSceneURL", editImageSceneURL.getText().toString().trim());
        requestBody.put("imageSpeedURL", editImageSpeedURL.getText().toString().trim());
        requestBody.put("imageCommunicationURL", editImageCommunicationURL.getText().toString().trim());
        ApiService apiService = ApiClient.getApiService();
        apiService.updateComplaints(complaintId, requestBody).enqueue(new Callback<upLoadComplaintURLModel>() {
            @Override
            public void onResponse(Call<upLoadComplaintURLModel> call, Response<upLoadComplaintURLModel> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(ModifyDetailsActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                    finish(); // 返回上一页
                } else {
                    Toast.makeText(ModifyDetailsActivity.this, "更新失败，请重试", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<upLoadComplaintURLModel> call, Throwable t) {
                Toast.makeText(ModifyDetailsActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void openImagePicker(EditText urlEditText, ImageView thumbnail) {
        // 这里可以启动系统相册、第三方图片选择器、或弹窗让用户粘贴URL
        Toast.makeText(this, "请选择图片或粘贴URL", Toast.LENGTH_SHORT).show();

        // 示例：模拟设置一个本地图片
        thumbnail.setImageResource(R.drawable.ic_launcher_foreground); // 示例图片
        urlEditText.setText("https://example.com/images/signal.jpg"); // 示例 URL
    }

}
